from sqlalchemy.orm import Session

from app.models.user_address import UserAddress
from app.schemas.user_address import AddressBase, AddressResponse


def address_list(db: Session, user_id: int) -> list[AddressResponse]:
    """查询用户地址"""
    address_list = db.query(UserAddress).filter(
        UserAddress.user_id == user_id).all()
    return [
        AddressResponse.model_validate(address) for address in address_list
    ]


def get_defult(db: Session, user_id: int) -> int:
    """获取用户默认地址"""
    address = db.query(UserAddress).filter(
        UserAddress.user_id == user_id).filter(
            UserAddress.is_default == True).one()
    return address.address_id


def address_save(db: Session, user_id: int, address: AddressBase) -> bool:
    """添加地址"""
    address_db = UserAddress(**address.model_dump(), user_id=user_id)
    db.add(address_db)
    db.commit()
    return True

def address_edit(db: Session, user_id: int, address: AddressBase) -> bool:
    """编辑用户地址"""
    # 1. 先查出来（确保是这条用户的）
    address_db = db.query(UserAddress).filter(
        UserAddress.id == address.id,
        UserAddress.user_id == user_id
    ).first()

    if not address_db:
        return False  # 或者 raise HTTPException(404, "地址不存在")

    for key, value in address.model_dump(exclude={"id"}).items():
        setattr(address_db, key, value)

    db.commit()
    return True

def set_defult(db: Session, user_id: int, addressId: int) -> bool:
    """设置默认值"""
    address_db = db.query(UserAddress).filter(
        UserAddress.user_id == user_id).filter(
            UserAddress.is_default == True).one()
    if not address_db:
        address.is_default = False
    address = db.query(UserAddress).filter(
        UserAddress.address_id == addressId).one()
    address.is_default = True
    db.commit()
    db.refresh()
    return True

def del_address(db: Session, addressId: int) -> bool:
    """删除"""
    address_db = db.query(UserAddress).filter(
        UserAddress.address_id == addressId).one()
    if not address_db:
        return False
    db.delete(address_db)
    db.commit()
    return True

def get_address(db: Session, addressId: int) -> AddressResponse:
    """获取收货地址详情"""
    address_db = db.query(UserAddress).filter(
        UserAddress.address_id == addressId).one()
    return AddressResponse.model_validate(address_db)
